<template>
  <div id="app"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import request from '@/api/request.js';
import '../assets/iconfont/iconfont.css';
// import dayjs from 'dayjs';

// import {gcj02towgs84} from '@/utils/translate.js'

// 气体单位
const GAS_UNITS = {
  pm2p5: 'μg/m³',
  co: 'mg/m³',
  no2: 'μg/m³',
  pm10: 'μg/m³',
  so2: 'mg/m³',
  o3: 'μg/m³',
};

import monitor_img from '../assets/monitor.png';

export default {
  data() {
    return {
      // map 地图对象实例
      map: null,
    };
  },
  mounted() {
    this._createBaseMap();
  },
  methods: {
    _createBaseMap() {
      mapboxgl.accessToken =
        'pk.eyJ1IjoiY2hhbnBmIiwiYSI6ImNsNG1qMDExejAwNDgzam8zcGtiMW5sNmwifQ.J4K5kbkjtcAABsmIW7Z0Tw';

      const map = new mapboxgl.Map({
        container: 'app',
        //自己绘制的样式地图令牌
        antialias: true, //抗锯齿
        style: 'mapbox://styles/mapbox/dark-v10',
        center: [114.13982985118895, 22.626926735280392],
        // center: [-75.789, 41.874],
        zoom: 11,
        // maxZoom: 5.99,
        // minZoom: 4,
        // zoom: 5,
      });
      this.map = map;
      window.map = map;

      // zoom变化时打印zoom值
      map.on('zoom', function (e) {
        console.log('zoom :>> ', e.target.getZoom());
      });

      const taskArr = [
        request.get('../monitor_station.geojson'),
        request.get(
          'https://devapi.qweather.com/v7/air/now?key=0f19220d67a24dc6bb86fadf60800562&location=101280601'
        ),
      ];

      Promise.all(taskArr).then((data) => {
        console.log('data :>> ', data);
        let [geojsonData, { station: stations }] = data;

        // 两个数据不一致，需要以和风接口的数据为准
        geojsonData.features = geojsonData.features.filter((item) => {
          for (const item2 of stations) {
            if (item?.properties?.POI_ID === item2?.id) {
              // const vanillaLng = item.geometry.coordinates[0];
              // const vanillaLat = item.geometry.coordinates[1];

              // const convertResult = gcj02towgs84(
              //   vanillaLat,
              //   vanillaLng
              // );

              // item.geometry.coordinates[0] = convertResult[1];
              // item.geometry.coordinates[1] = convertResult[0];

              return item;
            }
          }
          return false;
        });
        this.mergeArrProp(geojsonData.features, stations);
        console.log('geojsonData.features :>> ', geojsonData.features);
        console.log('geojsonData :>> ', geojsonData);
        // console.log('stations :>> ', stations);

        map.on('load', () => {
          map.loadImage(monitor_img, function (error, image) {
            if (error) throw error;
            map.addImage('monitor', image, { sdf: true });

            // 添加图标层
            map.addLayer({
              id: 'monitor-icons-layer',
              type: 'symbol',
              source: {
                type: 'geojson',
                data: geojsonData,
              },
              layout: {
                'icon-image': 'monitor',
                'icon-size': 0.13,
                // 'icon-offset': [0, -65],
                'text-field': ['get', 'aqi'],
                // 将文字偏移到图标下方
                'text-offset': [0, 1.4],
              },
              paint: {
                'icon-opacity': [
                  'interpolate',
                  ['linear'],
                  ['zoom'],
                  // zoom 比8.5小隐藏
                  8.5,
                  0,
                  // 否则显示
                  10,
                  1,
                ],
                'icon-color': '#FF0000',
              },
            });

            // 添加文字层
            // map.addLayer({
            //   id: 'monitor-text-layer',
            //   type: 'symbol',
            //   source: {
            //     type: 'geojson',
            //     data: geojsonData,
            //   },
            // });
          });
          map.addSource('monitor-station-source', {
            type: 'geojson',
            data: geojsonData,
            generateId: true,
          });
          map.addLayer({
            id: 'monitor-station-layer',
            type: 'circle',
            source: 'monitor-station-source',
            // 根据 AQI 的值实现颜色变换
            paint: {
              'circle-color': [
                'interpolate',
                ['linear'],
                ['to-number', ['get', 'aqi']],
                0,
                'gray',
                0.1,
                '#0FFF00',
                50,
                'green',
                100,
                'yellow',
                150,
                'orange',
                200,
                'red',
                300,
                'purple',
                500,
                '#A00000',
              ],
              'circle-radius': [
                'interpolate',
                ['linear'],
                ['zoom'],
                8.5,
                0,
                // 9.9,
                // ['/', ['zoom'], 1.5],
                10,
                8,
              ],
              'circle-opacity': [
                'interpolate',
                ['linear'],
                ['zoom'],
                // zoom 比8.5小隐藏
                8.5,
                0,
                // 否则显示
                10,
                1,
              ],
              'circle-translate': [0, -11.5],
            },
          });
          map.on('click', 'monitor-points-layer', function (e) {
            const features = map.queryRenderedFeatures(e.point, {
              layers: ['monitor-station-layer'],
            });
            if (features.length) {
              const clickedPoint = features[0];
              console.log('clickedPoint :>> ', clickedPoint);
              window.clickPoint = clickedPoint;
              // 1. 地图重定位
              this.flyTo({
                center: clickedPoint.geometry.coordinates,
                speed: 1,
              });
            }
          });

          map.on('mousemove', 'monitor-points-layer', function (e) {
            // 移动到对应的点上时，鼠标的样式变为小手
            this.getCanvas().style.cursor = 'pointer';
            // 如果没有对应的 features 则什么都不做
            if (e.features.length === 0) return;

            const hoverPopups =
              document.getElementsByClassName('custom-hover-popup');
            // 之前有弹出框的话则移除
            if (hoverPopups[0]) hoverPopups[0].remove();

            const currentFeature = e.features[0];
            console.log('currentFeature :>> ', currentFeature);
            const props = currentFeature.properties;
            const PM2D5Val = `${props['pm2p5']}${GAS_UNITS['pm2p5']}`;
            const coVal = `${props['co']}${GAS_UNITS['co']}`;
            const no2Val = `${props['no2']}${GAS_UNITS['no2']}`;
            const pm10Val = `${props['pm10']}${GAS_UNITS['pm10']}`;
            const so2Val = `${props['so2']}${GAS_UNITS['so2']}`;
            const o3Val = `${props['o3']}${GAS_UNITS['o3']}`;
            const stationName = `${props['name']}空气质量监测站`;
            // 创建一个hover弹出层
            new mapboxgl.Popup({
              closeButton: false,
              className: 'custom-hover-popup',
            })
              .setLngLat(currentFeature.geometry.coordinates)
              .setHTML(
                `
          			<div>
          				<div style="font-weight:bold;">${stationName}</div>
          				<div>PM2.5: ${PM2D5Val}</div>
          				<div>CO: ${coVal}</div>
          				<div>NO2: ${no2Val}</div>
          				<div>PM10: ${pm10Val}</div>
          				<div>SO2: ${so2Val}</div>
          				<div >O3: ${o3Val}</div>
          			</div>
          			`
              )
              .addTo(this);
          });

          map.on('mouseleave', 'monitor-points-layer', function () {
            this.getCanvas().style.cursor = '';
            const hoverPopups =
              document.getElementsByClassName('custom-hover-popup');
            // 之前有弹出框的话则移除
            if (hoverPopups[0]) hoverPopups[0].remove();
          });

          // geojsonData.features.forEach((item) => {});

          // for (const marker of geojsonData.features) {
          //   // const wrapper = document.createElement('div');
          //   // Create a DOM element for each marker.
          //   // const width = 20;
          //   // const height = 20;

          //   const span = document.createElement('div');
          //   span.className = 'iconfont icon-phone-full';
          //   // el.style.backgroundImage = `url(../monitor.png)`;
          //   // el.style.width = `${width}px`;
          //   // el.style.height = `${height}px`;
          //   // el.style.backgroundSize = '100%';

          //   span.addEventListener('click', function () {
          //     window.alert(marker.properties.message);
          //     this.remove();
          //   });

          //   // Add markers to the map.
          //   new mapboxgl.Marker(span)
          //     .setLngLat(marker.geometry.coordinates)
          //     .addTo(map);
          // }

          map.on('click', (e) => {
            console.log(e);
          });
        });
      });
    },
    // 给定两个数组，将第二个数组每一个元素的所有属性整合到第一个数组中
    mergeArrProp(arr1, arr2) {
      for (const item1 of arr1) {
        for (const item2 of arr2) {
          if (item1?.properties?.POI_ID === item2?.id) {
            item1.properties = {
              ...item1.properties,
              ...item2,
            };
            break;
          }
        }
      }
    },
  },
  beforeDestroy() {
    // this.map.removeLayer('custom-vector-tile-layer');
    this.map.remove();
    this.map = null;
  },
};
</script>

<style>
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}

#app {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
}

.mapboxgl-popup {
  padding-bottom: 12px;
}
</style>
